package com.mdr.imedera.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mdr.imedera.exception.wx.MatrialException;
import com.mdr.imedera.util.request.RequestUtils;
import com.mdr.imedera.util.wx.AccessToken;
import io.netty.handler.codec.json.JsonObjectDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.Request;

import java.util.HashMap;
import java.util.Map;

/**
 * @PACKAGE_NAME: com.mdr.imedera.service
 * @NAME: wxb
 * @USER: Administrator
 * @DATE: 2020/10/22
 * @TIME: 14:46
 * @YEAR: 2020
 * @MONTH: 10
 * @MONTH_NAME_SHORT: 10月
 * @MONTH_NAME_FULL: 十月
 * @DAY: 22
 * @DAY_NAME_SHORT: 周四
 * @DAY_NAME_FULL: 星期四
 * @HOUR: 14
 * @MINUTE: 46
 * @PROJECT_NAME: imedera
 **/
@Slf4j
@Service
public class MaterialServiceImpl implements MaterialService{

    @Autowired private AccessToken accessToken;

    /**
     * 1.获取永久素材的列表，也包含公众号在公众平台官网素材管理模块中新建的图文消息、语音、视频等素材
     * 2、临时素材无法通过本接口获取
     * 3.调用该接口需https协议
     * 4.method:post
     * 5.请求参数必须为json字符串
     */
    private static String getMaterialListUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?";


    @Override
    public JSONObject getMaterialList(String type, Integer pageIndex, Integer pageSize) {
        String url = accessToken.setAccessTokenAddToUrl(getMaterialListUrl);
        //请求参数放到集合中
        Map<String,String> map = new HashMap<>();
        map.put("type","news");
        map.put("offset", RequestUtils.getOffset(pageIndex, pageSize).toString());
        map.put("count",pageSize.toString());
        //发送请求
        String request = RequestUtils.postSend(url,JSONObject.toJSONString(map));
        log.info("获取素材列表:{}",request);
        //校验请求结果是否成功
        JSONObject jsonObject = JSONObject.parseObject(request);
        if(jsonObject.getString("errcode")!=null){
            throw new MatrialException(jsonObject.getString("errcode"));
        }
        return JSON.parseObject(request);
    }


}
